package org.ddevil.data.set;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.ddevil.data.Attribute;
import org.ddevil.data.Data;

/**
 * @author Rich
 */
public class BeanDataSet<T extends Data> implements DataSet<T>, Iterable<T> {

	private static final long serialVersionUID = 4182947923556783213L;
	private List<T> data;

	public BeanDataSet() {
		data = new ArrayList<T>();
	}
	public BeanDataSet(List<T> data) {
		this.data = new ArrayList<T>(data);
	}

	public void clear() {
		data.clear();
	}

	public T exportRecord(int rowNum) {
		return data.get(rowNum);
	}

	/**
	 * {@inheritDoc}
	 */
	public DataSet<T> exportRecords(int... indices) {
		BeanDataSet<T> rv = new BeanDataSet<T>();
		for (int i : indices) {
			rv.importRecord(exportRecord(i));
		}
		return rv;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object getDataAt(int rowIndex, String id) {
		return exportRecord(rowIndex).getValue(id);
	}

	/**
	 * {@inheritDoc}
	 */
	public List<String> getIdentifiers() {
		if (size() == 0) {
			return Collections.EMPTY_LIST;
		}
		List<String> ret = new ArrayList<String>();
		for (Attribute a : exportRecord(0)) {
			ret.add(a.getId());
		}
		return ret;
	}

	/**
	 * {@inheritDoc}
	 */
	public void importRecord(T inData) {
		data.add(inData);
	}

	/**
	 * {@inheritDoc}
	 */
	public void importRecords(DataSet<T> inData) {
		for (int i = 0; i < inData.size(); i++) {
			importRecord(inData.exportRecord(i));
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void removeRecord(int index) {
		data.remove(index);
	}

	/**
	 * {@inheritDoc}
	 */
	public void setDataAt(int rowIndex, String id, Object val) {
		data.get(rowIndex).setDataItem(id, val);
	}

	/**
	 * {@inheritDoc}
	 */
	public int size() {
		return data.size();
	}

	public Iterator<T> iterator() {
		return data.iterator();
	}

}
